import {
  routelist
} from '@/router'

// import { topRouterMap } from "@/router/topRouter";
import Layout from '@/layout' // 页面整体布局
import Empty from '@/empty' //空页面布局
import XEUtils from 'xe-utils'

let loadChildMenu = (childrenData) => {
  let itemChildren = []
  if (childrenData && childrenData.length > 0) {
    childrenData.forEach((itenChild) => {
      itemChildren.push({
        id: itenChild.id,
        hidden: itenChild.hidden,
        meta: {
          title: itenChild.meta.title,
          icon: itenChild.meta.icon,
        },
        name: itenChild.name,
        path: itenChild.path,
        component: itenChild.component == "Empty" ? Empty : () => import(`@/page${itenChild.component}`),
        children: itenChild.children && itenChild.children.length > 0 ? loadChildMenu(itenChild.children) : null
      })
    })
  }
  return itemChildren;
}

/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */

function loadRouterList(data) {
  let router = [];
  data.forEach(item => {
    if (item.component == "Layout") { //有子菜单
      item.name = "Layout" + item.name;
      item.component = Layout;
      item.children = loadChildMenu(item.children);
      router.push(item);
    } else { //只有一级菜单
      router.push({
        hidden: item.hidden,
        name: "Layout" + item.name,
        path: "/",
        component: Layout,
        children: loadChildMenu([item])
      });
    }
  });
  return router;
}


const permission = {
  state: {
    routers: routelist,
    addRouters: [],
    routersFlag:true,
    browserHeaderTitle: 'vue测试项目'
  },
  getters: {
    permission_routers: state => state.routers, // 所有路由
    addRouters: state => state.addRouters, // 权限过滤路由
    routers_flag: state => state.routersFlag, // 路由标识
    browserHeaderTitle: state => state.browserHeaderTitle,
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers // 权限路由
      state.routers = routelist.concat(routers) // 总路由
      state.routersFlag = false
    },
    SET_BROWSER_HEADER_TITLE: (state, browserHeaderTitle) => {
      state.browserHeaderTitle = browserHeaderTitle
    },
  },
  actions: {
    // 根据角色，重新设置权限路由;并保存到vuex中,SET_ROUTERS;
    generateRoutes({
      commit
    }, data) {
      return new Promise(resolve => {
        let router = loadRouterList(data)
        commit('SET_ROUTERS', router)
        resolve(router)
      })
    }
  }
}

export default permission
